<template>
	<view class="info-body">
		<view class="top-container">
			<view class="top-card">
				<view class="top-no">
					<span>维修单号</span>
					<span>{{params.repair_code}}</span>
				</view>
				<span class="repair-title">{{params.repair_name}}</span>
				<up-line length="calc(100% - 40rpx)" margin="20rpx 20rpx"></up-line>
				<view>
					<view class="title-item"><span>维修人 {{params.repair_personnel_name}}</span></view>
					<view class="title-item"><span>故障说明 {{params.fault_description}}</span></view>
					<view class="title-item"><span>维修时间 {{params.repair_date}}</span></view>
					<view class="title-item"><span>期望修复日期 {{params.expect_repair_date}}</span></view>
				</view>
			</view>
			<view class="attachment">
				<span>附件</span>
				<!-- 附件列表 -->
				<view v-if="fileList.length > 0" class="file-list">
					<view v-for="(file, index) in fileList" :key="index" class="file-item">
						<text class="file-name" @click="handleDownloadFile(file)">{{file.name}}</text>
					</view>
				</view>
				<view v-else class="no-attachment">
					<text>暂无附件</text>
				</view>
			</view>
		</view>
		<view class="content-container">
			<view class="content-top">
				<span>资产列表</span>
				<span>共计:{{total}}</span>
			</view>
			<scroll-view scroll-y="true">
				<view class="content-data" v-for="(item,index) in dataList" :key="index">
					<view class="content-info">
						<image :src="`${BASE_URL}/File/GetImage?fileId=${item.image}`"></image>
						<view class="content-info-right">
							<span>{{item.asset_name}}</span>
							<span>使用部门 {{item.department_name}}</span>
							<span>使用人 {{item.user_name}}</span>
							<span>存放地点 {{item.local_name}}</span>
							<span>资产编码 {{item.asset_code}}</span>
							<span>标签编码 {{ item.label_number }}</span>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<view class="footer-bar">
			<up-button type="primary" text="返回" @click="goBack" v-if="pageType === 'detail'"></up-button>
		</view>

		<!-- 审核模式下的底部按钮 -->
		<view class="audit-btns" v-if="pageType === 'audit'">
			<up-button type="default" text="驳回" @click="showRejectDialog"></up-button>
			<up-button type="primary" text="通过" @click="approve"></up-button>
		</view>

		<!-- 驳回原因弹窗 -->
		<up-popup :show="showRejectPopup" :round="10" mode="center" @close="closeRejectDialog">
			<view class="reject-popup">
				<view class="reject-title">驳回原因</view>
				<view class="reject-content">
					<up-textarea v-model="rejectReason" placeholder="请输入驳回原因" :maxlength="200"></up-textarea>
				</view>
				<view class="reject-buttons">
					<up-button type="default" text="取消" @click="closeRejectDialog"></up-button>
					<up-button type="primary" text="确定" @click="confirmReject"></up-button>
				</view>
			</view>
		</up-popup>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad,
		onUnload
	} from "@dcloudio/uni-app";
	import http, {
		BASE_URL
	} from "@/api/request";

	const params = ref({});
	const dataList = ref([]);
	const total = ref(0);
	const dataParams = ref([]);
	// 详情页（detail）还是审核页（audit）
	const pageType = ref("");
	// 审核相关状态
	const showRejectPopup = ref(false);
	const rejectReason = ref('');
	const fileList = ref([]); // 文件列表

	onLoad((options) => {
		pageType.value = options.type;
		params.value = uni.getStorageSync("assetWarrantyData")
		console.log(params.value,'123')
		const data = {
			code: "getAssetListByRepairCode",
			allColumnFilter: true,
			filters: [{
				name: 'repair_code',
				value: params.value.repair_code
			}],
			pageInput: {
				currentPage: 1,
				pageSize: 999
			},
			permissionKey: ""
		};
		http.post("/api/module/GetViewTable", data).then((res) => {
			if (res.code && res.isSuccess) {
				dataList.value = res.result.viewTable
				total.value = res.result.viewTable.length
				for (let i = 0; i < total.value; i++) {
					dataParams.value.push({
						id: res.result.viewTable[i].id,
						fileId: '',
						money: '',
						repair_desc: ''
					})
				}
			}
		});
		// 加载附件
		loadAttachments();
	})

	onUnload(() => {
		uni.removeStorageSync("assetWarrantyData");
	});
	
	// 加载附件
		const loadAttachments = async () => {
			if (!params.value.id) return;
			
			const postData = {
				linkId: "1",
				taskId: params.value.id,
			};
			
			try {
				const { code, isSuccess, result } = await http.post(
					"/api/file/GetTaskLinkedFiles",
					postData
				);
				
				if (code && isSuccess && result) {
					fileList.value = result.map(item => ({
						id: item.id,
						name: item.fileName + "  " + item.userName + "  " + item.creationTime,
						url: `/File/Download?fileId=${item.id}`,
					}));
				}
			} catch (error) {
				console.error("加载附件失败:", error);
			}
		};
		
		// 下载文件
			const handleDownloadFile = (file) => {
				uni.downloadFile({
					url: BASE_URL + file.url,
					success: (res) => {
						if (res.statusCode === 200) {
							plus.runtime.openFile(res.tempFilePath, {}, (e) => {
								uni.showModal({
									title: "无法打开文件",
									content: "请安装 WPS Office 或 QQ 浏览器等可打开该文件的应用",
									confirmText: "去安装",
									success: (modalRes) => {
									if (modalRes.confirm) {
										try {
											plus.runtime.openURL('market://details?id=com.tencent.mtt', () => {
												plus.runtime.openURL('https://browser.qq.com');
											});
										} catch (e) {
											plus.runtime.openURL('https://browser.qq.com');
										}
									}
									},
								});
							});
						}
					},
					fail: (err) => {
						console.error("下载失败", err);
						uni.showToast({
							title: "下载失败",
							icon: "none"
						});
					},
				});
			};
	// 显示驳回弹窗
	const showRejectDialog = () => {
		rejectReason.value = '';
		showRejectPopup.value = true;
	};

	// 关闭驳回弹窗
	const closeRejectDialog = () => {
		showRejectPopup.value = false;
	};

	// 确认驳回
	const confirmReject = () => {
		if (!rejectReason.value.trim()) {
			uni.showToast({
				title: '请输入驳回原因',
				icon: 'none'
			});
			return;
		}
		submitAudit('REJECTED');
		closeRejectDialog();
	};

	// 审核通过
	const approve = () => {
		uni.showModal({
			title: '审核确认',
			content: `确定通过报修单 ${params.value.repair_code} 的审核吗？`,
			cancelText: '取消',
			confirmText: '确定',
			success: (res) => {
				if (res.confirm) {
					submitAudit('APPROVED');
				}
			}
		});
	};

	// 提交审核结果
	const submitAudit = (auditResult) => {
		uni.showLoading({
			title: '提交中...'
		});

		http.post('/api/module/Invoke', {
			pageCode: "assetwarranty",
			params: {
				args: [{
						name: "interfaceCode",
						value: "Assetwarranty.updateStatus"
					},
					{
						name: "repairMstr",
						value: {
							"id": params.value.id,
							"repair_state": auditResult,
							// TODO 驳回原因！repair 表里没有这个字段，驳回后期需要重做的
						}
					}
				]
			},
			methodName: "updateStatus"
		}).then(res => {
			uni.hideLoading();
			if (res.isSuccess) {
				uni.showToast({
					title: auditResult === 'APPROVED' ? '审核通过成功' : '驳回成功',
					icon: 'success'
				});
				setTimeout(() => {
					goBack();
				}, 1500);
			} else {
				uni.showToast({
					title: res.error || '操作失败',
					icon: 'none'
				});
			}
		}).catch(() => {
			uni.hideLoading();
			uni.showToast({
				title: '网络异常，请稍后重试',
				icon: 'none'
			});
		});
	};

	// 返回上一页
	const goBack = () => {
		uni.navigateBack();
	}
</script>

<style lang="scss" scoped>
	.info-body {
		height: calc(100vh - var(--window-top, 0px));
	}

	.top-container {

		height: 620rpx;
		background: #4792FD;
		display: flex;
		flex-direction: column;
		align-items: center;

		.top-card {
			margin-top: 20rpx;
			height: 420rpx;
			width: 90%;
			background-color: #4D96FF;
			border-radius: 10rpx;

			.top-no {
				margin: 20rpx;
				height: 45rpx;
				display: flex;
				align-items: center;

				&>span:first-child {
					background-color: white;
					padding: 10rpx;
					border-radius: 8rpx;
					color: #4792FD;
				}

				&>span:last-child {
					margin-left: 30rpx;
					color: white;
				}
			}

			.repair-title {
				margin: 20rpx;
				color: #D8ECF1;
			}

			view {
				margin: 0 20rpx;

				.title-item {
					margin: 20rpx 0;
					color: #D8ECF1;
				}
			}
		}

		.attachment {
			margin-top: 20rpx;
						width: 100%;
						min-height: 140rpx;
						width: 90%;
						background-color: #4D96FF;
						border-radius: 10rpx;
						padding: 20rpx;
						box-sizing: border-box;
			
						&>span {
							display: block;
							color: #D8ECF1;
							margin-bottom: 20rpx;
						}
						.file-list {
										.file-item {
											padding: 10rpx 0;
											border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);
											
											.file-name {
												color: #D8ECF1;
												font-size: 28rpx;
												word-break: break-all;
											}
										}
									}
									
									.no-attachment {
										color: #D8ECF1;
										font-size: 28rpx;
										text-align: center;
										padding: 20rpx 0;
									}
		}
	}

	.content-container {
		display: flex;
		flex-direction: column;
		height: calc(100vh - 790rpx);
		overflow-y: auto;

		.content-top {
			display: flex;
			align-items: center;
			padding: 0 20rpx;
			color: #4D84D2;
			height: 100rpx;
			justify-content: center;
			width: 100%;
			background-color: white;

			&>span:last-child {
				margin-left: auto;
			}
		}

		.content-data {
			width: calc(100% - 40rpx);
			margin: 20rpx 20rpx 60rpx 20rpx;
			background-color: white;
			border-radius: 10rpx;
			padding: 10rpx;

			.content-info {
				display: flex;
				padding: 10rpx;
				width: 100%;
				border-bottom: 1px solid #ccc;

				image {
					height: 250rpx;
					width: 250rpx;
				}

				.content-info-right {
					margin-left: 20rpx;
					display: flex;
					flex-direction: column;
					width: calc(100% - 260rpx);

					&>span:nth-child(1) {
						font-size: 1.3rem
					}

					&> :nth-child(n+2) {
						color: #CBCACE;
					}


				}
			}

			.content-form {
				width: calc(100% - 40rpx);
				margin: 20rpx;
			}
		}
	}

	.footer-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx 30rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.audit-btns {
		display: flex;
	}

	/* 驳回弹窗样式 */
	.reject-popup {
		width: 600rpx;
		padding: 40rpx;
		border-radius: 20rpx;
	}

	.reject-title {
		font-size: 32rpx;
		font-weight: bold;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.reject-content {
		margin-bottom: 30rpx;
	}

	.reject-buttons {
		display: flex;
		justify-content: space-between;
	}
</style>